import {PlusOutlined} from '@ant-design/icons';
import {Button, Divider, message, Input, Drawer, Badge , Select, Form, Modal, Tag, DatePicker} from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import React, {useState, useRef} from 'react';
import {PageContainer, FooterToolbar} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import OrderApprovalForm from './components/OrderApprovalForm';
import {queryOrder, removeOrder, updateOrder, addOrder, approvalOrder} from "@/services/order";




const TableList = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [formType, setFormType] = useState(1) // 1:新增 2:更新 3：详情
  const [showApprove, setShowApprove] = useState(true) // 是否显示审批详情
  const [activekey, setActiveKey] = useState('tab1');
  const actionRef = useRef();
  const [formRef] = Form.useForm();
  const [row, setRow] = useState();
  const [selectedRow, setSelectedRow] = useState({});
  const { Option } = Select;
  const { RangePicker } = DatePicker;
  const handleApprovalModalVisible = (record)=>{
    formRef.setFieldsValue({
      ...record
    })
    setSelectedRow(record)
    handleModalVisible(true)
    setFormType(2)
    setShowApprove(true)
  }

  const handleDetailModalVisible = (record, status)=>{
    setShowApprove(status)
    formRef.setFieldsValue({
      ...record
    })
    setSelectedRow(record)
    handleModalVisible(true)
    setFormType(3)
  }

  const handleApproval = async (fields) => {
    fields.orderId = selectedRow.orderId;
    fields.productType = selectedRow.productType;
    const hide = message.loading('正在审核');

    try {
      await approvalOrder({...fields}).then(res=>{
        if(res && res.status === '0') {
          handleModalVisible(false)
          message.success('审核成功');
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }else {
          message.error(res.message);
        }
      });
      hide();
      return true;
    } catch (error) {
      hide();
      message.error('审核失败请重试！');
      return false;
    }
  };


  const onSubmit = (orderDatas)=>{
    const success = handleApproval(orderDatas);
    // if (actionRef.current) {
    //   actionRef.current.reload();
    // }
  }



  const noApprovalColumns = [
    {
      title: '序号',
      dataIndex: 'key',
      hideInForm: true,
      width: 80,
      hideInSearch: true,
      render: (text, record, index, action) => {
        return `${index + 1}`
      }
    },
    {
      title: '订单编号',
      dataIndex: 'orderCode',
      width: 150,
      tip: '订单编号是唯一的',
      hideInForm: true,
      copyable: true,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input placeholder={'请输入订单编号'}/>;
      }
    },
    // {
    //   title: '产品名称',
    //   dataIndex: 'productName',
    //   width: 150,
    //   formItemProps: {
    //     rules: [
    //       {
    //         max: 10,
    //         message: '产品名称最大长度为10'
    //       },
    //       {
    //         whitespace: true,
    //         message: '请不要输入空格'
    //       }
    //     ],
    //   },
    //   valueType: 'input',
    //   renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
    //     return <Input maxLength={11} {...fieldProps} placeholder={'请输入产品名称'}/>;
    //   }
    // },
    {
      title: '产品编码',
      dataIndex: 'productCode',
      width: 150,
    },
    {
      title: '生产编号',
      dataIndex: 'productionNo',
      width: 150,
      hideInSearch: true,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input maxLength={11} placeholder={'请输入生产编号'}/>;
      }
    },
    {
      title: '客户名称',
      dataIndex: 'custName',
      width: 150,
    },
    {
      title: '客户型号',
      dataIndex: 'clientCode',
      width: 150,
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '订货量(PCS)',
      width: 150,
      dataIndex: 'orderNum',
      hideInSearch: true
    },
    {
      title: '订单创建人',
      dataIndex: 'realName',
      width: 150,
      hideInSearch: true,
      hideInForm: true
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 200,
      sorter: true,
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return (
          <RangePicker showTime />
        );
      }
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a onClick={() => handleDetailModalVisible(record, false)}>
          详情
        </a>,
        <Divider style={{display: record.orderStatus === 1? 'block': 'none'}} type="vertical"/>,
        <a style={{display: record.orderStatus === 1? 'block': 'none'}} onClick={() => handleApprovalModalVisible(record)}>审批</a>,
      ],
    },
  ];

  const approvaledColumns = [
    {
      title: '序号',
      dataIndex: 'key',
      width: 80,
      hideInForm: true,
      hideInSearch: true,
      render: (text, record, index, action) => {
        return `${index + 1}`
      }
    },
    {
      title: '订单编号',
      dataIndex: 'orderCode',
      tip: '订单编号是唯一的',
      width: 150,
      hideInForm: true,
      copyable: true,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input placeholder={'请输入订单编号'}/>;
      }
    },
    // {
    //   title: '产品名称',
    //   dataIndex: 'productName',
    //   width: 150,
    //   formItemProps: {
    //     rules: [
    //       {
    //         max: 10,
    //         message: '产品名称最大长度为10'
    //       },
    //       {
    //         whitespace: true,
    //         message: '请不要输入空格'
    //       }
    //     ],
    //   },
    //   valueType: 'input',
    //   renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
    //     return <Input maxLength={11} {...fieldProps} placeholder={'请输入产品名称'}/>;
    //   }
    // },
    {
      title: '产品编码',
      dataIndex: 'productCode',
      width: 150,
    },
    {
      title: '客户名称',
      dataIndex: 'custName',
      width: 150,
    },
    {
      title: '客户型号',
      dataIndex: 'clientCode',
      hideInSearch: true,
      hideInTable: true,
      width: 150,
    },
    {
      title: '订货量(PCS)',
      dataIndex: 'orderNum',
      hideInSearch: true,
      width: 150,
    },
    {
      title: '订单创建人',
      dataIndex: 'realName',
      width: 150,
      hideInSearch: true,
      hideInForm: true
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      hideInForm: true,
      hideInSearch: true,
      valueType: 'date',
      width: 200,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return (
          <RangePicker showTime />
        );
      }
    },
    {
      title: '审批人',
      dataIndex: 'approvalByName',
      hideInSearch: true,
      hideInForm: true,
      width: 150,
    },
    {
      title: '审批时间',
      dataIndex: 'approvalTime',
      valueType: 'date',
      hideInSearch: true,
      width: 200,
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a onClick={() => handleDetailModalVisible(record, true)}>
          详情
        </a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable
        style={{display: createModalVisible? 'none': 'block'}}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolbar={{
          menu: {
            type: 'tab',
            activeKey: activekey,
            items: [
              {
                key: 'tab1',
                label: <span>待审批</span>,
              },
              {
                key: 'tab2',
                label: <span>已审批</span>,
              }
            ],
            onChange: (key) => {
              setActiveKey(key);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            },
          },
        }}
        request={async (params, sorter, filter) => {
          const param = activekey === 'tab1'? {
            ...params,
            pageNum: params.current,
            approvalBy: JSON.parse(sessionStorage.getItem('user')).sysUser.userId,
            orderStatus: 1 // 查询待审批订单
          }: {
            ...params,
            pageNum: params.current,
            approvalBy: JSON.parse(sessionStorage.getItem('user')).sysUser.userId,
            orderStatusMin: 2 // 查询已审批订单
          };
          const res = await queryOrder(param)
          return {
            data: res.result.records,
            success: true,
            total: res.result.total
          }
        }}
        columns={activekey ==='tab1'? noApprovalColumns: approvaledColumns}
      />
      {
        createModalVisible? <OrderApprovalForm
          onCancel={() => handleModalVisible(false)}
          visible={createModalVisible}
          onSubmit={(orderData)=>onSubmit(orderData)}
          formType={formType}
          oldOrderData={selectedRow}
          approved={showApprove}
        >
        </OrderApprovalForm>: <></>
      }
    </PageContainer>
  );
};

export default TableList;
